package com.villaday.idf.activity;

import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.atuan.datepickerlibrary.CalendarUtil;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.villaday.idf.R;
import com.villaday.idf.adapter3.OrderDeatailsPopuAdapter;
import com.villaday.idf.adapter3.OrderInputResultAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.custom.CommonPopupWindow;
import com.villaday.idf.custom.ConfirmReturnDialog;
import com.villaday.idf.custom.LoadDialog;
import com.villaday.idf.custom.PayDialog;
import com.villaday.idf.model.PayEntity;
import com.villaday.idf.model.PayMent;
import com.villaday.idf.model3.CreatOrdersEntity;
import com.villaday.idf.model3.DataEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class OrderInputResultActivity extends BaseActivity {


    @BindView(R.id.iv_title)
    ImageView ivTitle;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_title_big)
    TextView tvTitleBig;
    @BindView(R.id.tv_title_en)
    TextView tvTitleEn;
    @BindView(R.id.tv_iir_title)
    TextView tvIirTitle;
    @BindView(R.id.tv_iir_time)
    TextView tvIirTime;
    @BindView(R.id.tv_oi_time_right)
    TextView tvOiTimeRight;
    @BindView(R.id.tv_oi_time_right_num)
    TextView tvOiTimeRightNum;
    @BindView(R.id.tv_iir_bottom)
    TextView tvIirBottom;
    @BindView(R.id.rv_iir_in)
    RecyclerView rvIirIn;
    @BindView(R.id.et_iir_phone)
    TextView etIirPhone;
    @BindView(R.id.et_iir_email)
    TextView etIirEmail;
    @BindView(R.id.tv_iir_feedBack)
    TextView tvIirFeedBack;
    @BindView(R.id.tv_oi_left)
    TextView tvOiLeft;
    @BindView(R.id.tv_oi_money)
    TextView tvOiMoney;
    @BindView(R.id.tv_oi_reduce)
    TextView tvOiReduce;
    @BindView(R.id.tv_oi_confirm)
    TextView tvOiConfirm;
    @BindView(R.id.tv_oi_details_more)
    TextView tvOiDetailsMore;
    @BindView(R.id.iv_oi_details)
    ImageView ivOiDetails;
    @BindView(R.id.ll_ol_details)
    LinearLayout llOlDetails;
    @BindView(R.id.ll_iir_email)
    LinearLayout llIirEmail;
    @BindView(R.id.ll_feedback)
    LinearLayout llFeedback;
    @BindView(R.id.ll_order_ir)
    LinearLayout llOrderIr;
    private CreatOrdersEntity.BodyBean mBodyBean;
    private List<CreatOrdersEntity.BodyBean.GuestsBean> guests;
    private CommonPopupWindow mPopuDetails;
    private String inDay;
    private LoadDialog loadDialog;


    @Override
    protected int getViewResId() {
        return R.layout.activity_order_input_result;
    }

    @Override
    protected void init() {
        super.init();
        Bundle bundle = getIntent().getExtras();


        String data = bundle.getString("data");
        mBodyBean = new Gson().fromJson(data, CreatOrdersEntity.class).getBody();

        inDay = getIntent().getExtras().getString("inDay");
        tvOiTimeRight.setText(inDay + "晚");

        String feedBack = getIntent().getExtras().getString("feedBack");

        tvIirTitle.setText(mBodyBean.getProduct().getChildProduct().getRoomName());
        tvIirBottom.setText(mBodyBean.getProduct().getChildProduct().getRules());


        CreatOrdersEntity.BodyBean.ProductBean product = mBodyBean.getProduct();
        CreatOrdersEntity.BodyBean.ProductBean.ChildProductBean childProduct = mBodyBean.getProduct().getChildProduct();

        tvIirTime.setText(CalendarUtil.FormatChangeString(childProduct.getCheckInDate()) + " - " + CalendarUtil.FormatChangeString(childProduct.getCheckOutDate()));
        //是否国外酒店
        if (product.getDistrict() == 3) {//国外酒店
            tvTitleBig.setVisibility(View.GONE);
            tvTitle.setVisibility(View.VISIBLE);
            tvTitle.setText(product.getName());
            tvTitleEn.setVisibility(View.VISIBLE);
            tvTitleEn.setText(product.getName());
        } else {
            tvTitleBig.setVisibility(View.VISIBLE);
            tvTitleBig.setText(product.getName());
            tvTitle.setVisibility(View.GONE);
            tvTitleEn.setVisibility(View.GONE);
        }


        tvOiMoney.setText(mBodyBean.getActualPriceValue() + "");

        guests = mBodyBean.getGuests();

        //初始化列表
        initRecycle();
        tvOiTimeRightNum.setText(guests.size() + "间");

        if (mBodyBean.getTotalDiscountAmountValue() != null && !mBodyBean.getTotalDiscountAmountValue().equals("0")) {
            tvOiReduce.setText(Html.fromHtml("已优惠 &yen;" + mBodyBean.getTotalDiscountAmountValue()));
        } else {
            tvOiReduce.setVisibility(View.GONE);
        }


        etIirPhone.setText(mBodyBean.getMobile());

        if (feedBack != null && feedBack.length() != 0) {
            tvIirFeedBack.setText(feedBack);
        } else {
            llFeedback.setVisibility(View.GONE);
        }

        if (mBodyBean.getGuests().get(0).getEmail() != null && mBodyBean.getGuests().get(0).getEmail().length() != 0) {
            etIirEmail.setText(mBodyBean.getGuests().get(0).getEmail());
        } else {
            llIirEmail.setVisibility(View.GONE);
        }

        if (mBodyBean.isAllowPayment()) {
            tvOiConfirm.setVisibility(View.VISIBLE);
        } else {
            tvOiConfirm.setVisibility(View.VISIBLE);
        }
    }

    private void initRecycle() {
        rvIirIn.setLayoutManager(new LinearLayoutManager(this, LinearLayout.VERTICAL, false));
        OrderInputResultAdapter orderInputResultAdapter = new OrderInputResultAdapter(this);
        rvIirIn.setAdapter(orderInputResultAdapter);
        orderInputResultAdapter.setData(guests);
    }


    @OnClick({R.id.tv_oi_confirm, R.id.iv_title, R.id.ll_ol_details})
    public void btnOnclick(View view) {
        switch (view.getId()) {
            case R.id.tv_oi_confirm:
                pay();
                break;
            case R.id.iv_title:
                ConfirmReturnDialog confirmDialog = ConfirmReturnDialog.newInstance("温馨提示", "您还没有完成支付哦", "我再想想", "立即支付");
                confirmDialog.setOnBtnClickListener(new ConfirmReturnDialog.OnBtnClickListener() {
                    @Override
                    public void onBtnClick(View view) {
                        pay();
                    }

                    @Override
                    public void onDeselect(View view) {
                        finish();
                    }
                });
                confirmDialog.show(getSupportFragmentManager(), "返回");
                break;
            case R.id.ll_ol_details:
                initPopupDetails();
                break;
        }
    }


    /**
     * 初始化popup
     */
    private void initPopupDetails() {
        mPopuDetails = new CommonPopupWindow(OrderInputResultActivity.this, R.layout.popu_money_details, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) {

            @Override
            protected void initView() {
                View view = getContentView();
                TextView tvPmd = (TextView) view.findViewById(R.id.tv_pmd);
                TextView tvMe = (TextView) view.findViewById(R.id.tv_md_me);
                LinearLayout llMe = (LinearLayout) view.findViewById(R.id.ll_md_me);

                TextView tvBalance = (TextView) view.findViewById(R.id.tv_md_balance);
                LinearLayout llBalance = (LinearLayout) view.findViewById(R.id.ll_md_balance);


                TextView tvReduceTitle = (TextView) view.findViewById(R.id.tv_reduce_title);
                TextView tvReduce = (TextView) view.findViewById(R.id.tv_md_reduce);
                LinearLayout llReduce = (LinearLayout) view.findViewById(R.id.ll_md_reduce);
                llReduce.setVisibility(View.GONE);
                TextView tvOld = (TextView) view.findViewById(R.id.tv_md_old);
                LinearLayout llOld = (LinearLayout) view.findViewById(R.id.ll_md_old);


                TextView tvMdMoney = (TextView) view.findViewById(R.id.tv_md_money);
//                float v = Float.parseFloat(mBodyBean.getActualPriceValue()) - Float.parseFloat(mBodyBean.getTotalDiscountAmountValue());
                tvMdMoney.setText(mBodyBean.getActualPriceValue());

                TextView tvMdConfirm = (TextView) view.findViewById(R.id.tv_md_confirm);
                tvMdConfirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopuDetails.getPopupWindow().dismiss();
                    }
                });

                RecyclerView rvDetails = (RecyclerView) view.findViewById(R.id.rv_md_details);


                if (mBodyBean.getDiscountAmountValue() != null && !mBodyBean.getDiscountAmountValue().equals("0")
                        && !mBodyBean.getDiscountAmountValue().equals("")) {
                    tvMe.setText(Html.fromHtml("- &yen;" + mBodyBean.getDiscountAmountValue()));
                } else {
                    llMe.setVisibility(View.GONE);
                }

                if (mBodyBean.getWalletDeductibleAmountValue() != null && !mBodyBean.getWalletDeductibleAmountValue().equals("0")
                        && !mBodyBean.getWalletDeductibleAmountValue().equals("")) {
                    tvBalance.setText(Html.fromHtml("- &yen;" + mBodyBean.getWalletDeductibleAmountValue()));
                }else {
                    llBalance.setVisibility(View.GONE);
                }


                llReduce.setVisibility(View.GONE);
                llOld.setVisibility(View.GONE);

                List<CreatOrdersEntity.BodyBean.ProductBean.ChildProductBean.PriceListBean> priceList = mBodyBean.getProduct().getChildProduct().getPriceList();

                List<DataEntity> list = new ArrayList<>();
                for (int i = 0; i < priceList.size(); i++) {
                    DataEntity dataEntity = new DataEntity();
                    dataEntity.setTitle(priceList.get(i).getDayValue());
                    dataEntity.setContent(priceList.get(i).getPriceValue());
                    list.add(dataEntity);
                }

                rvDetails.setLayoutManager(new LinearLayoutManager(OrderInputResultActivity.this, LinearLayoutManager.VERTICAL, false));
                OrderDeatailsPopuAdapter orderDeatailsPopuAdapter = new OrderDeatailsPopuAdapter(OrderInputResultActivity.this);
                rvDetails.setAdapter(orderDeatailsPopuAdapter);
                orderDeatailsPopuAdapter.setData(list);
            }

            @Override
            protected void initEvent() {
                WindowManager.LayoutParams attributes = getWindow().getAttributes();
                attributes.alpha = 0.3f;
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getWindow().setAttributes(attributes);
            }
        };
        mPopuDetails.getPopupWindow().setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams attributes = getWindow().getAttributes();
                attributes.alpha = 1.0f;
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getWindow().setAttributes(attributes);
            }
        });
        mPopuDetails.showAtLocation(llOrderIr, Gravity.BOTTOM, 0, 0);
    }

    public void pay() {
        final PayDialog payDialog = PayDialog.newInstance(mBodyBean.getActualPriceValue());
        payDialog.show(getFragmentManager());
        payDialog.setOnItemClickListener(new BaseDialog.OnItemClickListener() {
            @Override
            public void onItemClick(View v) {
                Map<String, Object> objectObjectHashMap = new HashMap<>();
                OkHttpUtil.postJson(OrderInputResultActivity.this, Constant.URL.pay, new PayMent(mBodyBean.getOrderNo(), 2), objectObjectHashMap, new OkHttpUtil.OnDataListener() {
                    @Override
                    public void onResponse(String url, String json) {
//                        dismissDialog();
                        if (!TextUtils.isEmpty(json)) {
                            LogeUtil.e("pay11", json);
                            SharedPreferencesUtil.saveWeOrderBoolean(OrderInputResultActivity.this, true);
                            SharedPreferencesUtil.saveWeOrderNum(OrderInputResultActivity.this, mBodyBean.getOrderNo());
                            PayEntity payEntity = new Gson().fromJson(json, PayEntity.class);
                            if ("200".equals(payEntity.getCode())) {
                                IWXAPI api = WXAPIFactory.createWXAPI(OrderInputResultActivity.this, Constant.ID.WeChat_APP_ID, true);
                                api.registerApp(Constant.ID.WeChat_APP_ID);
                                if (!api.isWXAppInstalled()) {//?????
                                    ToastUtil.initToast(OrderInputResultActivity.this, "??????");
                                    return;
                                }
                                PayEntity.BodyEntity body = payEntity.getBody();
                                PayReq req = new PayReq();
                                //req.appId = "wxf8b4f85f3a794e77";  // ??????appId
                                req.appId = body.getAppid();
                                req.partnerId = body.getPartnerid();
                                req.prepayId = body.getPrepayid();
                                req.nonceStr = body.getNoncestr();
                                req.timeStamp = body.getTimestamp();
                                req.packageValue = body.getPackageX();
                                req.sign = body.getSign();
                                req.extData = "app data";

                                // ?????????????????????????????????IWXMsg.registerApp???????????
                                api.sendReq(req);
                            } else {
                                ToastUtil.initToast(OrderInputResultActivity.this, payEntity.getMsg());
                            }
                        }
                    }

                    @Override
                    public void onFailure(String url, String error) {

                    }
                });

            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 停止加载框
     */
    protected void dismissDialog() {
        if (loadDialog != null) {
            loadDialog.dismiss();//获取信息后关闭对话框
        }
    }

    /**
     * 设置加载框
     */
    protected void showDialog() {
        if (loadDialog == null) {
            loadDialog = LoadDialog.newInstance("加载中");
            loadDialog.show(getSupportFragmentManager(), "loading");
        }
    }

}
